package com.zhsj.OkeHomeConsumption.ui.activity.entering;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseDialog;
import com.hjq.dialog.MenuDialog;
import com.hjq.dialog.WaitDialog;
import com.hjq.widget.CountdownView;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.MerchantTypeBean;
import com.zhsj.OkeHomeConsumption.empty.SelectCityEnity;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.MapActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.WebActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.entering.mvp.MerchantPresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.entering.mvp.MerchantUIInterFace;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ClearEditText;
import com.zhsj.OkeHomeConsumption.utils.CodeUtils;
import com.zhsj.OkeHomeConsumption.utils.SelectCityPicker;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;
import com.zhsj.OkeHomeConsumption.utils.StringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 商家入驻
 */
public final class EnteringActivity extends MyActivity implements MerchantUIInterFace {
    //选择城市
    @BindView(R.id.selet_city)
    ClearEditText seletCity;

    //请选择经营类型
    @BindView(R.id.operating_type)
    ClearEditText operatingType;

    //商户名称
    @BindView(R.id.merchant_name)
    ClearEditText merchantName;

    //详细地址
    @BindView(R.id.address)
    ClearEditText address;

    //负责人
    @BindView(R.id.principal)
    ClearEditText principal;

    //电话
    @BindView(R.id.phone)
    ClearEditText phone;

    //验证码
    @BindView(R.id.verification_code)
    ClearEditText verificationCode;

    //提交入驻申请
    @BindView(R.id.btn_test_login)
    Button btnTestLogin;


    //关于我们
    @BindView(R.id.guanyuwomen_lin)
    LinearLayout guanyuwomenLin;

    //入驻条件
    @BindView(R.id.tianjian_lin)
    LinearLayout tianjian_lin;


    //入驻理由
    @BindView(R.id.grounds_lin)
    LinearLayout groundsLin;

    //入驻流程
    @BindView(R.id.liucheng_lin)
    LinearLayout liuchengLin;

    @BindView(R.id.cv_register_countdown)
    CountdownView cvRegisterCountdown;

    //选择位置
    @BindView(R.id.map_name)
    ClearEditText mapName;

    private MerchantPresenter minePersonPresenter;
    /**
     * @Fields mSendSmsCodeCount : TODO 发送短信验证码计时器
     */
    private SendSmsCodeCount mSendSmsCodeCount = null;
    private ArrayList<SelectCityEnity> mSelectCityLists = null;
    private ArrayList<MerchantTypeBean> mMerchantTypeLists = null;

    private ArrayList<String> options1Items = new ArrayList<>();//省
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//市
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();//区

    private int proviceId = -1;//省
    private int mcityId = -1;//市
    private int districCountryId = -1;//区
    private int streetId;//街道

    private int categoryLevel1NameId;

    private String latitude = "";//纬度

    private String longitude = "";//经度

    private String shopLocation = "";//店铺定位



    @Override
    protected int getLayoutId() {
        return R.layout.entering_activity_enter;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_about_title;
    }

    @Override
    protected void initView() {
        mSendSmsCodeCount = new SendSmsCodeCount(60 * 1000, 100);
    }

    @Override
    protected void initData() {
        hideSoftKeyboard();
        minePersonPresenter = new MerchantPresenter(getActivity(), this);
        operatingType.setEnabled(true);
        operatingType.setCursorVisible(false);
        operatingType.setFocusable(false);
        operatingType.setFocusableInTouchMode(false);
        operatingType.setInputType(InputType.TYPE_NULL);
        seletCity.setEnabled(true);
        seletCity.setCursorVisible(false);
        seletCity.setFocusable(false);
        seletCity.setFocusableInTouchMode(false);
        seletCity.setInputType(InputType.TYPE_NULL);

        mapName.setEnabled(true);
        mapName.setCursorVisible(false);
        mapName.setFocusable(false);
        mapName.setFocusableInTouchMode(false);
        mapName.setInputType(InputType.TYPE_NULL);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private void empty() {


        if(latitude.equals("")||longitude.equals("")){
            toast("请选择店铺位置");
            return;
        }
        String city = seletCity.getText().toString();
        if (StringUtils.isEmpty(city)) {
            toast("请选择城市");
            return;
        }
        String operatingType_str = operatingType.getText().toString();
        if (StringUtils.isEmpty(operatingType_str)) {
            toast("请选择经营类型");
            return;
        }
        String merchantName_str = merchantName.getText().toString();
        if (StringUtils.isEmpty(merchantName_str)) {
            toast("请填写商户名称");
            return;
        }
        String address_str = address.getText().toString();
        if (StringUtils.isEmpty(address_str)) {
            toast("请填写详细地址");
            return;
        }
        String principal_str = principal.getText().toString();
        if (StringUtils.isEmpty(principal_str)) {
            toast("请填写负责人");
            return;
        }
        String strPhoneNum = phone.getText().toString().trim();
        if (TextUtils.isEmpty(strPhoneNum)) {
            toast("请填写手机号");
            return;
        }
        String verification = verificationCode.getText().toString().trim();
        if (TextUtils.isEmpty(verification)) {
            toast("请填写验证码");
            return;
        }

        Gson gson = new Gson();
//        String lifeDesireRelaListstr = gson.toJson(yiyuanlist);
        Map<String, Object> mapjson = new HashMap<>();

        mapjson.put("shopLocation", shopLocation);
        mapjson.put("cityName", city);
        mapjson.put("categoryLevel1Name", categoryLevel1NameId);
        mapjson.put("address", address_str);
        mapjson.put("shopLeader", principal_str);
        mapjson.put("provinceId", proviceId);//省id
        mapjson.put("cityId", mcityId);//市ID
        mapjson.put("districCountryId", districCountryId);//县ID
        mapjson.put("streetId", streetId);//街道id
        mapjson.put("shopName", merchantName_str);
        mapjson.put("latitude", latitude);
        mapjson.put("longitude", longitude);
        mapjson.put("shopMobile", strPhoneNum);
        mapjson.put("verifyCode", verification);
        String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
        minePersonPresenter.MerchantPost(lifeCityCopartnerDTO);
    }


    @OnClick({R.id.cv_register_countdown, R.id.selet_city, R.id.operating_type, R.id.merchant_name, R.id.address, R.id.principal,
            R.id.phone, R.id.verification_code, R.id.btn_test_login, R.id.guanyuwomen_lin, R.id.grounds_lin, R.id.liucheng_lin, R.id.tianjian_lin,R.id.map_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cv_register_countdown:
                // 发送验证码
                String strPhoneNum = phone.getText().toString().trim();
                if (TextUtils.isEmpty(strPhoneNum)) {
                    toast("请填写手机号");
                    cvRegisterCountdown.resetState();
                    return;
                }
                if (phone.getText().toString().length() != 11) {
                    toast("请输入正确的手机号码");
                    cvRegisterCountdown.resetState();
                    return;
                }
                SendCodevolleyPost(strPhoneNum);
                break;
            case R.id.map_name:
                //选择地图位置
                startActivityForResult(new Intent(this,MapActivity.class),1);
                break;
            case R.id.selet_city:
                minePersonPresenter.CityListPsot();
                break;
            case R.id.operating_type:
                minePersonPresenter.MerchantTypeGet();
                break;
            case R.id.merchant_name:
                break;
            case R.id.address:
                break;
            case R.id.principal:
                break;
            case R.id.phone:
                break;
            case R.id.verification_code:
                break;
            case R.id.btn_test_login:
                empty();
                break;
            case R.id.guanyuwomen_lin:
                Intent intent = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/2.html");
                startActivity(intent);
                break;
            case R.id.grounds_lin:
                Intent intent2 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/4.html");
                startActivity(intent2);
                break;
            case R.id.liucheng_lin:
                Intent intent3 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/11.html");
                startActivity(intent3);
                break;
            case R.id.tianjian_lin:
                Intent intent4 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/8.html");
                startActivity(intent4);
                break;
            case R.id.linerbtn:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode ==1){
            //地图页面返回
            if(resultCode == -1){
                latitude =  data.getStringExtra("latitude");//纬度
                longitude = data.getStringExtra("longitude");//经度
                shopLocation = data.getStringExtra("name");
                mapName.setText(shopLocation);
            }else{
                latitude =  "";//纬度
                longitude ="";//经度
                shopLocation = "";
                mapName.setText("");
            }
        }
    }

    /**
     * 申请城市合伙人
     */
    @Override
    public void MerchantPost(String context, String lifeShopCopartnerDTO) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                finish();
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("MerchantPost", "申请城市合伙人");
        }
    }

    /**
     * 获取城市列表
     */
    @Override
    public void CityListPsot(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
                // 数据对接正常
                mSelectCityLists = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<SelectCityEnity>>() {
                        }.getType());
                getSelectCity(mSelectCityLists);

            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("CityListPsot", "获取城市列表异常");
        }
    }

    /**
     * 获取经营类型
     */
    @Override
    public void MerchantTypeGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
                // 数据对接正常
                mMerchantTypeLists = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<MerchantTypeBean>>() {
                        }.getType());
                List<String> datalist = new ArrayList<>();
                for (int i = 0; i < mMerchantTypeLists.size(); i++) {
                    datalist.add(mMerchantTypeLists.get(i).getName());
                }
                MenuDialog(datalist);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("MerchantTypeGet", "获取经营类型异常");
        }
    }


    /**
     * 选择城市
     *
     * @param mSelectProviceEnities
     */
    private void getSelectCity(ArrayList<SelectCityEnity> mSelectProviceEnities) {
        SelectCityPicker selectCityPicker = new SelectCityPicker(getActivity(), mSelectProviceEnities);
        selectCityPicker.setHalfScreen(true);
        selectCityPicker.setCancelTextColor(R.color.colorAccent);
        selectCityPicker.setSubmitTextColor(R.color.colorAccent);
        selectCityPicker.setOnCitySelectListener(new SelectCityPicker.OnCitySelectListener() {
            @Override
            public void onCitySelect(String province, String city, String county, String town, int provinceId, int cityId, int countyId, int townId) {
                if (!province.equals("") && city.equals("") && county.equals("") && town.equals("")) {
                    seletCity.setText(province);
                } else if (!province.equals("") && !city.equals("") && !county.equals("") && town.equals("")) {
                    seletCity.setText(province + "-" + city + "-" + county);
                } else if (!province.equals("") && !city.equals("") && county.equals("") && town.equals("")) {
                    seletCity.setText(province + "-" + city);
                } else {
                    seletCity.setText(province + "-" + city + "-" + county + "-" + town);
                }
                proviceId = provinceId;
                mcityId = cityId;
                districCountryId = countyId;
                streetId = townId;
            }
        });
        selectCityPicker.show();
    }


    private void MenuDialog(List<String> datalist) {
        new MenuDialog.Builder(this)
                .setCancel("取消") // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(datalist)
                .setListener(new MenuDialog.OnListener() {

                    @Override
                    public void onSelected(Dialog dialog, int position, String text) {
                        operatingType.setText(text);
                        categoryLevel1NameId = mMerchantTypeLists.get(position).getId();
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        toast("取消了");
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
                .show();
    }

    /**
     * @Title: SendCodevolleyPost @Description: TODO 获取验证码异步线程 @param @param
     * strPhoneNum 输入的手机号 @return void 返回类型 @throws
     */
    public void SendCodevolleyPost(String strPhoneNum) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        String phoneString = CodeUtils.encryptAES(strPhoneNum, CodeUtils.password);
        mSendCodeHashMap.put("mobile", phoneString);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        paramMaps.put("mobile", phoneString);
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = new WaitDialog.Builder(this)
                .setMessage("加载中...") // 消息文本可以不用填写
                .show();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_SMSCODE, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                TimeOutHandler.pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        toast("验证码已发送");
                    } else {
                        TimeOutHandler.pDialogUtils.dismiss();
                        // showShortToast("验证码发送失败");
                    }
                } catch (Exception ex) {
                    TimeOutHandler.pDialogUtils.dismiss();
                }

            }

            @Override
            public void onFailure(Throwable e) {
                super.onFailure(e);
//                TimeOutHandler.pDialogUtils.dismiss();
//                TimeOutHandler.pDialogUtils = null;
            }
        });

    }

    /**
     * @author zhangpeisen
     * @ClassName: SendSmsCodeCount
     * @Description: TODO 发送短信验证码的线程
     * @date 2016年9月13日 下午4:41:30
     */
    class SendSmsCodeCount extends CountDownTimer {

        public SendSmsCodeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            cvRegisterCountdown.setEnabled(true);
            cvRegisterCountdown.setTextColor(Color.parseColor("#79AB1C"));
            cvRegisterCountdown.setGravity(Gravity.CENTER);
            cvRegisterCountdown.setTextSize(14);
            cvRegisterCountdown.setText("发送");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            cvRegisterCountdown.setEnabled(false);
            if (millisUntilFinished / 1000 == 0) {
                onFinish();
            } else {
                cvRegisterCountdown.setText(millisUntilFinished / 1000 + "");
                cvRegisterCountdown.setTextColor(Color.parseColor("#B2B2B2"));
                cvRegisterCountdown.setGravity(Gravity.CENTER);
                cvRegisterCountdown.setTextSize(14);
            }
        }
    }
}